import { Injectable } from '@nestjs/common'
import { PrismaService } from '../prisma/prisma.service'
import { Prisma } from '@prisma/client'

@Injectable()
export class WebArticleService {
    constructor(private readonly prisma: PrismaService) {}

    async list (query: { pageIndex: number, pageSize: number, categoryId?: number, title?: string }) {
        const list = await this.prisma.$queryRaw`
            SELECT
            id,
            title,
            intro,
            coverImg,
            viewCount,
            createTime,
            categoryId,
            (SELECT CAST(COUNT(1) AS REAL) FROM comment WHERE comment.articleId=article.id AND comment.status=1) AS commentCount,
            (SELECT [name] FROM category WHERE category.id=article.categoryId) AS categoryName 
            FROM article WHERE [status]=1 
            ${
                query.categoryId ? 
                Prisma.sql`AND categoryId=${query.categoryId}` : 
                Prisma.empty
            }
            ${
                query.title ? 
                Prisma.raw(`AND title LIKE '%${query.title}%'`) : 
                Prisma.empty
            }
            ORDER BY createTime DESC 
            LIMIT ${ Prisma.raw(`${query.pageSize} OFFSET ${(query.pageIndex - 1) * query.pageSize}`) }
        `

        const total = await this.prisma.$queryRaw`
            SELECT CAST(COUNT(1) AS REAL) AS total FROM article WHERE [status]=1 
            ${
                query.categoryId ? 
                Prisma.sql`AND categoryId=${query.categoryId}` : 
                Prisma.empty
            }
        `

        return { list, total: total[0].total }
    }

    async recommend () {
        // 查找阅读数最多的3篇文章作为推荐  
        const recommend = await this.prisma.article.findMany({
            where: { status: 1 },
            take: 3,
            orderBy: { viewCount: 'desc' },
            select: {
                id: true,
                title: true,
                intro: true,
                coverImg: true,
                createTime: true
            }
        })

        // 评论总数
        const commentCount = await this.prisma.comment.count({ where: { status: 1 } })

        // 访客总数
        const visitCount = await this.prisma.visit.count()

        // 公告
        const setting = await this.prisma.setting.findUnique({ where: { id: 1 } })

        return { recommend, commentCount, visitCount, setting }
    }

    async detail (id: number) {
		const detail = await this.prisma.$queryRaw`
            SELECT
            id,
            title,
			html,
            intro,
            keyword,
            coverImg,
            viewCount,
            createTime,
			updateTime,
            categoryId,
            (SELECT CAST(COUNT(1) AS REAL) FROM comment WHERE comment.articleId=article.id AND comment.status=1) AS commentCount,
            (SELECT [name] FROM category WHERE category.id=article.categoryId) AS categoryName 
            FROM article WHERE ${Prisma.sql`id=${id}`} AND [status]=1 LIMIT 1
        `

		await this.prisma.article.update({
			data: {
				viewCount: detail[0].viewCount + 1,
				updateTime: detail[0].updateTime
			},
			where: { id }
		})

        return detail[0]
    }

	async getCountOfArticleAndCategory () {
		const articleCount = await this.prisma.article.count({
			where: { status: 1 }
		})
		const categoryCount = await this.prisma.category.count()
		return { articleCount, categoryCount }	
	}
}
